package org.crag.cafca.gui.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.crag.cafca.beans.User;
import org.crag.cafca.db.SqlConnector;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Servlet used for intercept the register form data and test the ones entered. 
 * If the datas are correct, insert user into DB, if not, redirect the user to the registration page.  
 * Email, Match betwwen mail/confirmation and match between Password/confirmation are done by Ext-Js (js/registration.js)
 * @author Celien
 *
 */
@WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet 
{
	/**
	 * Logger log4j. See log4j doc for more information.
	 */
	private static Logger log = Logger.getLogger(new Throwable().getStackTrace()[0].getClassName());
		
	private static final long serialVersionUID = 1L;
	
	/*Associated view of the servlet*/
	private static final String ASSOCIATED_VIEW = "/WEB-INF/registration.jsp"; 
	
	/*String used to have an easier acces to the field of the registration form*/
	private static final String NAME_FIELD = "name"; 
	private static final String USERNAME_FIELD = "username"; 
	private static final String PWD_FIELD = "password"; 
	private static final String MAIL_FIELD = "email"; 
	
 
    public RegistrationServlet() {
        super();
    }

    /**
     * If nothing received, display the form
     * @see /WEB-INF/registration.jsp
     */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		this.getServletContext().getRequestDispatcher(ASSOCIATED_VIEW).forward(request, response);
	}


	/**
	 * If some data are sent, retrieve them and do some validation test. 
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
		/*Retrieve the sent data*/
		String name = getParam(request, NAME_FIELD); 
		String email = getParam(request, MAIL_FIELD); 
		String username = getParam(request, USERNAME_FIELD); 
		String password = getParam(request, PWD_FIELD); 
		
		JSONObject toSendBack = new JSONObject(); 
		JSONArray dataArray = new JSONArray(); 		
		JSONObject row1 = new JSONObject(); 
		
		SqlConnector sqlConnector = new SqlConnector();	
		
		if(sqlConnector.doesUsernameExist(username))
			row1.put(USERNAME_FIELD, "Username already exist, please choose another one"); 
		
		/*If everything is OK*/
		if(row1.length() == 0)
		{
			User user = new User(name, email, username, password); 		
			sqlConnector.insertUser(user);			
			sqlConnector.close(); 
			this.getServletContext().getRequestDispatcher(ASSOCIATED_VIEW).forward(request, response);
		}			
		else{			
			dataArray.put(row1); 
			toSendBack.put("data", dataArray); 
			toSendBack.put("success", true); 
			response.getWriter().print(toSendBack.toString());
			response.setStatus(HttpServletResponse.SC_OK);
			sqlConnector.close();
		}		
		
	}
	
	
	/**
	 * 
	 * @param request : The HttpRequest received
	 * @param field : Name of the concerned field
	 * @return The String which corresponding to the field's name of the resgistration form, Error if errors appeared. 
	 */
	private String getParam(HttpServletRequest request, String field){
		String result = request.getParameter(field); 
		if(result == null || result.trim().length() == 0){
			return "Error"; 
		}else{
			return result.trim(); 
		}
	}
	

}
